<template>
    <el-cascader :placeholder="placeholder" v-model="value" :rules="rules" :options="cityList" :props="cascaderProps" clearable :style="{ width: width }" />
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import type { CascaderProps, FormRules } from "element-plus";
import { getByPid } from "@/utils/city";

//定义城市集合
const cityList = ref<any[]>([]);

//父传子
interface Props {
    width?: string;
    placeholder?: string;
    rules?: Array<FormRules> | null;
}
withDefaults(defineProps<Props>(), {
    width: "100%",
    placeholder: "请选择城市",
    rules: null,
});

const cascaderProps: CascaderProps = {
    lazy: true,
    expandTrigger: "hover" as const,
    lazyLoad(node: any, resolve: any) {
        resolve(
            getByPid(node.value ? node.value : 1)?.map((city: any) => {
                return {
                    value: city.id,
                    label: city.name,
                    leaf: node.level >= 2,
                };
            })
        );
    },
};

//计算属性获取城市数组
const value = computed({
    get: () => [provinceId.value, cityId.value, countyId.value],
    set: (arr: Array<number> | undefined) => {
        if (!arr) return;
        provinceId.value = arr[0];
        cityId.value = arr[1];
        countyId.value = arr[2];
    },
});

//接收父组件传入的参数
const provinceId = defineModel<Number>("provinceId", { type: Number, default: null });
const cityId = defineModel<Number>("cityId", { type: Number, default: null });
const countyId = defineModel<Number>("countyId", { type: Number, default: null });
</script>

<style scoped lang="less"></style>
